package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.ParseState;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * http://www.51cto.com/ 51cto
 *  abc
 */
public class _51ctoNewsAnalyse implements AnalyseNews{
	
	public boolean isDetailPage(String url) {
		boolean bRet=false;
		String[] regex={
				"http://.*.51cto.com/art/[0-9]{6}/[0-9]*.htm",
				"http://.*.51cto.com/.*-[0-9]*.htm"
				};
		if(url.startsWith("http://mobile.51cto.com/mobile")){
			return false;
		}
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		news.setUrl(url);

		String title=null;
		String content=null;
		Long date=null;
		String dateStr=null;
		Document doc=Jsoup.parse(htmltxt);
		title =doc.select("div.wznr h2").text();
		dateStr=doc.select("dl dt em").text();
		date=DateUtils.matchDate(dateStr);
		doc.select("#content .page").remove();
		doc.select("#content .docu").remove();
		doc.select("#content span:contains(原文：)").remove();
		content=doc.select("div.main_left").html();
		if(StringUtils.isBlank(title)||date==null){
			if("51CTO首页".equals(title)){
				news.setUpdateUrl(ParseState.NOTDETAIL.toString());
				return news;
			}
		}
		/**
		 * 初始化、截取 、设置作者信息*******************************************
		 *
		 * */
		String str=null;
		String author=null;
		str=doc.select("dl dt span:eq(0)").text();
		author=StringUtils.substringBetween(str,"佚名","字号");
		news.setAuthor(author);
		/**
		 *                        	 **************************end *************************
		 *
		 **/

		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setDate(date);

		return news;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
	public static void main(String[] args) {
		_51ctoNewsAnalyse a=new _51ctoNewsAnalyse();
		String url="http://cloud.51cto.com/art/201506/481573.htm";
//		String url="http://developer.51cto.com/art/201308/407576.htm";
		String fromatUrl=UrlArgumentTop.FromatUrl(url);
		System.out.println("url="+fromatUrl);
		System.out.println(a.isDetailPage(fromatUrl));
		UrlMeta meta=CrawlHTML.responseToURL(fromatUrl);
		NewsMeta parserHtml=a.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate() {
		return false;
	}
}
